import { ButtonProps } from '@/Util/Constant'
import * as PIXI from 'pixi.js'

export class Button {
    button: PIXI.Container = new PIXI.Container()
    private rect: PIXI.Graphics = new PIXI.Graphics()
    private container: PIXI.Container
    private text: string | number
    private bgColor?: string
    private hanlder?: () => void
    private posX?: number
    private posY?: number
    private width?: number
    private height?: number
    private scaleSize?: number
    private buttonText: PIXI.Text;
    constructor(props: ButtonProps) {
        this.container = props.container
        this.text = props.text
        this.bgColor = props.bgColor
        this.hanlder = props.handler
        this.posX = props.posX
        this.posY = props.posY
        this.width = props.width
        this.height = props.height
        this.scaleSize = props.scaleSize || 1
        this.container.scale.set(this.scaleSize)
        this.init()
    }
    init() {
        this.createButton()
    }
    createButton() {
        //创建文字
        this.buttonText = new PIXI.Text(this.text, {
            fontFamily: "Arial",
            fill: 0xffffff,
            fontSize: 25,
            align: "center",
            dropShadow: true,
            dropShadowColor: "orange",
            dropShadowBlur: 4,
            dropShadowAngle: Math.PI / 2,
            dropShadowDistance: 2,
        }) as PIXI.Text;
        //创建盒子
        this.rect.beginFill(this.bgColor || 'blue', 1)
        this.rect.drawRoundedRect(0, 0, this.width || 120, this.height || 40, 20)
        this.rect.endFill()
        this.rect.addChild(this.buttonText)
        this.buttonText.x = (this.rect.width - this.buttonText.width) / 2
        this.buttonText.y = (this.rect.height - this.buttonText.height) / 2
        this.button.addChild(this.rect)
        //绑定事件
        this.setCursor(this.button)
        if (this.hanlder) this.bindEvent(this.button, 'click', this.hanlder);
        // 添加到父级容器
        this.button.x = this.posX || 0
        this.button.y = this.posY || 0
        this.button.scale.set(0.8, 0.8)
        this.container.addChild(this.button)
    }

    setButtonText(newText: string | number) {
        this.buttonText.text = newText
        this.buttonText.x = (this.rect.width - this.buttonText.width) / 2
        this.buttonText.y = (this.rect.height - this.buttonText.height) / 2
    }

    bindEvent(sprite: PIXI.DisplayObject, eventType: string, callback: any) {
        (sprite as any).interactive = true;
        (sprite as any).on(eventType, callback)
    }
    hidden() {
        this.container.visible = false
    }
    setCursor(ele: any) {
        this.bindEvent(ele, 'mouseenter', () => {
            document.body.style.cursor = 'pointer'
        })
        this.bindEvent(ele, 'mouseleave', () => {
            document.body.style.cursor = 'default'
        })
    }
}